package com.note.simpleadmin.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

public class FileUtil {
	protected Log log = LogFactory.getLog(getClass());

	/**
	 * @param request
	 * @param dir
	 * 
	 * @return
	 */
	public static List<Map<String, String>> fileupload(HttpServletRequest request,
                                                       String dir, String baseUrl) {
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		// 创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 判断 request 是否有文件上传,即多部分请求
		if (multipartResolver.isMultipart(request)) {
			// 转换成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				// 取得上传文件
				MultipartFile file = multiRequest.getFile(iter.next());
				if (file != null) {
					// 取得当前上传文件的文件名称
					String originalFilename = file.getOriginalFilename();
					// 如果名称不为“”,说明该文件存在，否则说明该文件不存在
					if (originalFilename.trim() != "") {
						// 重命名上传后的文件名
						try {
							String fileType = originalFilename
									.substring(originalFilename
											.lastIndexOf(".") + 1);
							UUID uuid = UUID.randomUUID();
							System.out.println("dir=" + dir);
							// 定义上传路径
							File localFile = new File(dir + "/" + uuid
									+ "." + fileType);
							localFile.getParentFile().mkdirs();
							localFile.createNewFile();
							//将文件复制到本地
							file.transferTo(localFile);;
							Map<String,String> doc=new HashMap<String,String>();
							doc.put("realName",originalFilename);
							doc.put("fileName",uuid + "." + fileType);
							doc.put("type",fileType);
							doc.put("url",baseUrl+uuid + "." + fileType);
							long length = localFile.length();
							doc.put("size",length+"");
							list.add(doc);
							// document.setCreateTime("");
						} catch (IllegalStateException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
		}
		return list;
	}

}
